package com.zengchen.user.auth;

import com.zengchen.common.bean.ErrorCodeConts;
import com.zengchen.common.bean.ServerException;
import com.zengchen.common.utils.JWTUtils;
import com.zengchen.user.config.JwtConfig;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class CheckLoginAspect {

    @Autowired
    private JwtConfig jwtConfig;

    @Before("@annotation(com.zengchen.user.auth.CheckLogin)")
    public void checkLogin(){
        try {
            log.info("checkLogin start.......");
            // 1.从请求的Header里取出token
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("WX-TOKEN");
            log.info("checkLogin token = {}",token);
            // 2.检查token是否有效
            Boolean isValid = JWTUtils.validateToken(token, jwtConfig.getSecret());
            if (!isValid) {
                log.info("checkLogin token 无效，未登录！");
                throw new ServerException(ErrorCodeConts.UNAUTHORIZED);
            }
            log.info("checkLogin token 有效，已登录！");
            // 3.将用户id存放到 Attribute 里
            Claims claimsFromToken = JWTUtils.getClaimsFromToken(token, jwtConfig.getSecret());
            request.setAttribute("memberId", claimsFromToken.get("memberId"));
        } catch (Throwable e) {
            throw new ServerException(ErrorCodeConts.UNAUTHORIZED);
        }
    }
}
